package lion.framework.core.task;

import java.util.Date;

import lion.framework.core.task.builder.ScheduleBuilderManager;
import lombok.Getter;
import lombok.Setter;

/**
 * 任务日程，日程由任务和任务触发器构成，触发器用于判断任务是否是时候该执行了。
 *
 * <pre>
 * time   2013 2013年7月16日 下午4:35:11
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */

public class Schedule implements ISchedule {

	private IAutoTask task;
	@Getter
	private ITaskTimerRule timerRule;
	@Setter
	@Getter
	private int executedTimes = 0;
	@Setter
	@Getter
	private Date lastRunTime = null;
	@Setter
	@Getter
	private Date nextRunTime = null;
	private boolean havaError = false;

	@Setter
	@Getter
	private String args;

	@Setter
	private TaskStatus status;

	@Getter
	private String id;
	@Getter
	private String clusterId;

	public Schedule(String id, IAutoTask task, ITaskTimerRule timerRule, String clusterId) {

		this.id = id;
		this.task = task;
		this.timerRule = timerRule;
		this.clusterId = clusterId;
		this.status = TaskStatus.WAITING;

	}

	public Schedule(String id, IAutoTask task, ITaskTimerRule timerRule, String clusterId, String args) {

		this(id, task, timerRule, clusterId);
		this.args = args;

	}

	/**
	 * 判断该日程是否需要运行（1，通过触发器判断，2，通过次数限制判断，3，通过任务的起止时间判断）
	 */
	@Override
	public boolean isTimeToRun() {

		if (this.status != TaskStatus.WAITING) { return false; }
		if (this.timerRule.isExpired()) {
			this.setStatus(TaskStatus.EXPIRED);
			return false;
		}
		if (this.havaError && this.timerRule.isStopOnError()) {
			this.setStatus(TaskStatus.STOP);
			return false;
		}
		// check timesLimited
		if (this.timerRule.getTimesLimited() > 0 && this.executedTimes >= this.timerRule.getTimesLimited()) {
			this.setStatus(TaskStatus.EXPIRED);
			return false;
		}
		return this.timerRule.checkRunTime(this.lastRunTime);
	}

	@Override
	public IAutoTask getTask() {

		return task;
	}

	//
	@Override
	public void setError(Throwable e) {

		this.havaError = true;
	}

	@Override
	public void sync() {

	}

	@Override
	public String getType() {

		return ScheduleBuilderManager.DEFAULT_BUILDER_NAME;
	}

}
